%% ex2.m
% set dir: src/
close all;
clear; clc;

% Load image
imgC = imread("../data/cameraman.tif");
imgE = imread("../data/einstein.tif");

% cameraman
iC = getI(imgC);
sCrow = mean(scanLine4e(imgC,iC(:,1),"row"),2);
sCcol = mean(scanLine4e(imgC,iC(:,2),"column"),1);
figure(1)
subplot(3,1,1)
imshow(imgC)
axis off
hold on
line([0,256],[128,128],'Color','red')
line([128,128],[0,256],'Color','red')
hold off
subplot(3,1,2)
plot(sCrow)
xlim([0,256])
title("Grayscale in center row")
subplot(3,1,3)
plot(sCcol)
title("Grayscale in center column")
xlim([0,256])
saveas(gcf,"../assets/cameraman_centerGrayscale.png")

% einstein
iE = getI(imgE);
sErow = mean(scanLine4e(imgE,iE(:,1),"row"),2);
sEcol = mean(scanLine4e(imgE,iE(:,2),"column"),1);
figure(2)
subplot(3,1,1)
imshow(imgE)
axis off
hold on
line([0,800],[339,339],'Color','red')
line([400,400],[0,679],'Color','red')
hold off
subplot(3,1,2)
plot(sErow)
xlim([0,679])
title("Grayscale in center row")
subplot(3,1,3)
plot(sEcol)
title("Grayscale in center column")
xlim([0,800])
saveas(gcf,"../assets/einstein_centerGrayscale.png") 

%% getI
function I = getI(img)
    % If row(column)'s size is plural, calculate the mean grayscale of the two
    % lines in the middle. If the size is singular, then scan the floor(sz/2)+1
    % as the center row(column).
    
    % Check image size
    sz = size(img);

    I = zeros(2,2);

    for i=1:2
        if rem(sz(i),2)==0
            I(i,:) = [sz(i)/2, sz(i)/2+1];
        elseif rem(sz(i),2)~=0
            I(i,:) = [floor(sz(i)/2)+1,floor(sz(i)/2)+1];
        end
    end

end


%% scanLine4e
function s = scanLine4e(f, I, loc)
    % Returns the grayscale value of a specified row or column in an image.
    % f(matrix): grayscale matrix.
    % I(int): number of row or column.
    % loc(str): Select row or column.

    % param loc check
    if isempty(loc)
        loc = "row";
    elseif loc~="row"&&loc~="column"
        error("ERROR IN PARAMS, PLEASE CHECK PARA::LOC")
    end

    % read row/column
    if loc == "column"
        s = f(I,:);
    elseif loc == "row"
        s = f(:,I);
    end

end
